#include "workspace.h"

workspace::workspace(QWidget *parent): QWidget(parent){
	QGridLayout *layoutWidget = new QGridLayout( this );
	tabMaster = new QTabWidget(this);
	tabMaster->setTabsClosable(true);
	tabMaster->setTabShape ( QTabWidget::Triangular );
	tabMaster->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
	layoutWidget->addWidget(tabMaster);
	setLayout(layoutWidget);
	connect ( tabMaster,	SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
}

workspace::~workspace(void){
	int size = tabs.size();
	for (int i = 0; i < size; i++)
		closeDiagram(tabs[0]);
}

void workspace::closeTab(int i){closeDiagram(tabs[i]);}

void workspace::openDiagram(diagram *d){

	int temp0=tabs.indexOf(d->id);
	if (diagrams.contains(d->id)&&temp0!=-1)
	{
		return;
	}
	QGraphicsView *view = new QGraphicsView();
	view->setScene(d);
	view->setDragMode ( QGraphicsView::RubberBandDrag );
	view->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
	tabMaster->addTab(view, d->name);
	tabs << d->id;
	diagrams[d->id]=d;
	tabMaster->setCurrentIndex ( tabs.size()-1 );
	tabMaster->setTabEnabled(tabs.size()-1, true );
	view->setEnabled(true);
	/*if (tabs.size() == 1)
		tabMaster->setCurrentIndex ( 0 );*/
}

void workspace::closeDiagram(int diagram_id){
	if (diagrams.contains(diagram_id)){
	diagrams[diagram_id]->disconnect();
	diagrams.remove(diagram_id);
	int temp0=tabs.indexOf(diagram_id);
	tabMaster->removeTab(temp0);
	if (temp0!=-1)
		tabs.remove(temp0);
	}
}
void workspace::clear(){
	int size = tabs.size();
	for (int i = 0; i < size; i++)
		closeDiagram(tabs[0]);
}

void workspace::setScale(int value){
	double factor = (double)value / 100;
	QGraphicsView *view = (QGraphicsView *)tabMaster->currentWidget();
	view->resetMatrix();
	//view->resetScale();
    view->scale(factor, factor);
}

diagram *workspace::activeDiagram(){
	if (tabs.isEmpty())
		return NULL;
	else
		return diagrams[tabs[tabMaster->currentIndex()]];
}
